package com.yootk.action;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.WebAsyncTask;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

/**
 * WebAsyncTask处理异步线程
 */
@Slf4j
@RestController
@RequestMapping("webAsync/*")
public class WebAsyncAction {

    @RequestMapping("task")
    public Object task(String msg) {
        log.info("外部线程：{}", Thread.currentThread().getName());
        Callable<String> callable = new Callable<>() {
            @Override
            public String call() throws Exception {
                log.info("内部线程：{}", Thread.currentThread().getName());
                TimeUnit.SECONDS.sleep(1);  // 模拟操作延迟
                return "【ECHO】" + msg;
            }
        };
        WebAsyncTask task = new WebAsyncTask(200, callable);    // 200毫秒解决异步处理
        task.onTimeout(new Callable<String>() {     // 超时线程
            @Override
            public String call() throws Exception {
                log.info("超时线程：{}", Thread.currentThread().getName());
                return "【ERROR】" + msg;
            }
        });
        return task;
    }
}
